package kuzha.runtime;

import java.util.Map;

import kuzha.KuzhaObject;

public class ListPattern extends CasePattern {
	public final CasePattern[] pats;
	public final CasePattern tail;
	
	private ListPattern(CasePattern[] pats, CasePattern tail) {
		if (pats == null)
			throw new IllegalArgumentException();
		this.pats = (CasePattern[]) pats.clone();
		this.tail = tail;
	}
	
	@Override
	public boolean match(KuzhaObject value, Map<String, KuzhaObject> vars) {
		if (value instanceof KzList) {
			KzList list = (KzList) value;
			if (pats.length == list.size() || (tail != null && pats.length < list.size())) {
				for (int i = 0; i < pats.length; i++) {
					if (!pats[i].match(list.get(i), vars)) {
						return false;
					}
				}
				if (tail != null) {
					if (!tail.match(list.slice(pats.length), vars)) {
						return false;
					}
				}
				return true;
			}
		}
		return false;
	}
	
	public static ListPattern valueOf(CasePattern[] pats, CasePattern tail) {
		return new ListPattern(pats, tail);
	}
}
